package javaSocket;

import cn.hutool.core.thread.ThreadFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class BIOServer {
    private static final ThreadFactory threadFactory = new ThreadFactoryBuilder().setNamePrefix("my-thread-").build();
    private static final ThreadPoolExecutor executor = new ThreadPoolExecutor(
            5, 10, 10,
            TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(100),
            threadFactory,
            new ThreadPoolExecutor.AbortPolicy()
    );

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("服务端启动成功");
        while (true){
            Socket socket = serverSocket.accept();
            System.out.println("监听到一个客户端");
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    handle(socket);
                }
            });
        }
    }
    private static void handle(Socket socket){
        try {
            byte[] bytes = new byte[1024];
            InputStream inputStream = socket.getInputStream();
            while (true){
                System.out.println(Thread.currentThread().getName());
                int read = inputStream.read(bytes);
                if (read != -1 ){
                    System.out.println(new String(bytes,0,read));
                }else {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            System.out.println("关闭client的连接");
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
